/**
 * 自动埋点
 */
import { ReportType } from './constant';
import { ReportParams } from './types';
import Utils from './utils';
export default class AutomaticBurialPoint {
	private readonly config = {
		attributeName: 'track', // 定义的的data-track属性名
		maxDepth: 5, // DOM树最大遍历深度
		capture: true, // 使用捕获阶段
		passive: true, // 不阻止默认事件
	};
	constructor(private callback: (params: ReportParams) => void) {
		Utils.log('自动埋点初始化成功');
		this.init();
	}

	eventHandler(event: Event) {
		const target = event.target as HTMLElement;
		if (!target) return;
		let depth = 0;
		const selectors = [];
		selectors.push(target);
		let reportData = target.dataset[this.config.attributeName];
		let parentNode = target.parentNode as HTMLElement;

		while (!reportData && parentNode && depth < this.config.maxDepth) {
			// 检查是否为文档节点
			if (parentNode.nodeType === Node.DOCUMENT_NODE) {
				return;
			}
			// 检查是否为元素节点 (Element.ELEMENT_NODE === 1)
			if (parentNode.nodeType !== Node.ELEMENT_NODE) {
				parentNode = parentNode.parentNode as HTMLElement;
				continue;
			}
			if (parentNode.tagName.toLocaleUpperCase() === 'BODY') {
				return;
			}
			selectors.push(parentNode);
			reportData = parentNode.dataset[this.config.attributeName];
			// 向上遍历
			parentNode = parentNode.parentNode as HTMLElement;
			depth++;
		}
		if (!reportData) return;
		this.callback({
			type: ReportType.AUTOMATIC_BURIAL_POINT,
			message: '自动埋点',
			data: reportData,
			selector: Utils.getSelectors(selectors),
		});
	}

	init() {
		document.addEventListener('click', this.eventHandler.bind(this), {
			capture: this.config.capture,
			passive: this.config.passive,
		});
	}
}
